import { useEffect, useState } from 'react';

import { VscRobot } from 'react-icons/vsc';
import { CiUser } from 'react-icons/ci';
import { useService } from '@flowgram.ai/free-layout-editor';
import { BubbleDataType, RolesType } from '@ant-design/x/es/bubble/BubbleList';
import { Bubble, Conversations, Sender, XStream } from '@ant-design/x';

import { CustomService } from '@/services';
import { cn } from '@/lib/utils';

import { Dialog, DialogContent, DialogHeader, DialogTitle } from '../ui/dialog';
import { Card } from '../ui/card';
import { Button } from '../ui/button';

export function RichAiChatBox({
  flowId,
  open,
  onOpenChange,
}: {
  flowId: number;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}) {
  const [conversationsItems, setConversationsItems] = useState<{ key: string; label: string }[]>(
    []
  );
  const [SessionId, setSessionId] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [content, setContent] = useState('');
  const [messages, setMessages] = useState<BubbleDataType[]>([]);
  const customService = useService(CustomService);

  console.log('flowId:', flowId);

  const loadConversations = () => {
    if (flowId == 0) {
      return;
    }
    customService.getSessionList(flowId).then((res) => {
      console.log('res', res);
      const convestions = res.map((item) => ({
        key: item.SessionId,
        label: item.Name,
      }));
      setConversationsItems(convestions);
    });
    customService.runFlow(flowId).then((res) => {
      console.log('runFlow:', res);
    });
  };

  useEffect(() => {
    setSessionId('');
    setIsLoading(false);
    setMessages([]);
    setContent('');
    if (open) {
      loadConversations();
    }
  }, [open, customService]);

  const CreateConversation = () => {
    setMessages([]);
  };

  const loadMessages = (id: string) => {
    customService.getSession(id).then((res) => {
      const msgs = res.map((item) => ({
        content: item.Content,
        role: item.Role,
      }));
      setMessages(msgs);
      console.log('loadMessages:', res);
    });
  };

  const handleActiveChange = (key: string) => {
    loadMessages(key);
    setSessionId(key);
  };

  const handleSubmit = async (value: string) => {
    setIsLoading(true);
    setContent('');
    const oldMessage = [...messages, { content: value, role: 'user' }];
    var newMessage = '';
    setMessages(oldMessage);
    customService
      .getFlowMessage(flowId, SessionId, value)
      .then(async (stream) => {
        for await (const chunk of XStream({
          readableStream: stream,
        })) {
          if (chunk && chunk.event === 'message') {
            newMessage += chunk.data;
            setMessages([...oldMessage, { content: newMessage, role: 'assistant' }]);
          }
        }
      })
      .catch((err) => {
        console.log('err:', err);
      })
      .finally(() => {
        setIsLoading(false);
      });
    console.log(value);
  };

  const roles: RolesType = {
    assistant: {
      placement: 'start',
      typing: true,

      avatar: <VscRobot />,
    },
    user: {
      placement: 'end',
      avatar: <CiUser />,
    },
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent
        className={cn('flex flex-col w-[80vw] h-[80vh] md:max-w-none md:max-h-none p-4')}
      >
        <DialogHeader className={cn('h-6 md:max-h-none gap-1 ')}>
          <DialogTitle>Ai对话</DialogTitle>
        </DialogHeader>
        <div className="flex flex-row w-full md:max-w-none h-full md:max-h-none gap-4">
          <Card className="min-w-[180px] flex-col h-full gap-4 px-1">
            <Button onClick={CreateConversation}>新建会话</Button>
            <Conversations
              items={conversationsItems}
              activeKey={SessionId}
              onActiveChange={handleActiveChange}
            />
          </Card>
          <Card className="flex-1 flex-col h-full gap-4 px-2">
            <Bubble.List items={messages} roles={roles} autoScroll className="flex-1" />
            <Sender
              value={content}
              onChange={setContent}
              loading={isLoading}
              onSubmit={handleSubmit}
            />
          </Card>
        </div>
      </DialogContent>
    </Dialog>
  );
}
